#include "mywidget.h"
#include "ui_mywidget.h"
#include<QPainter>

mywidget::mywidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::mywidget)
{
    ui->setupUi(this);

    //使用定时器
    timer =new QTimer();
    //定时器有timeout信号
    //信号槽
    connect(timer,SIGNAL(timeout()),this,SLOT(timeout()));
    resize(917,522);

    //初始化蛇身
    QRectF rect(300,200,nodeWidth,nodeHeight);
    snake.append(rect);
    addTop();
    addTop();

    //初始化食物
    addNewReward();
}

mywidget::~mywidget()
{
    delete ui;
}

//控制方向
void mywidget::keyPressEvent(QKeyEvent *event)
{
    switch(event ->key())
    {
    case Qt::Key_Up:
        if(moveFlag !=DIR_DOWN)
        {
            moveFlag =DIR_UP;
        }
        break;
    case Qt::Key_Down:
        if(moveFlag !=DIR_UP)
        {
            moveFlag =DIR_DOWN;
        }
        break;
    case Qt::Key_Left:
        if(moveFlag !=DIR_RIGHT)
        {
            moveFlag =DIR_LEFT;
        }
        break;
    case Qt::Key_Right:
        if(moveFlag !=DIR_LEFT)
        {
            moveFlag =DIR_RIGHT;
        }
        break;
    case Qt::Key_Space:
        if(gameStart ==false)
        {
            gameStart =true;
            //启动定时器
            timer->start(time);
        }
        else{
            gameStart =false;
            timer->stop();
        }
        break;
    default:
        break;

    }
}


void mywidget::timeout()
{
    // 判断蛇头和圆点是否重合
    int count= 1;
    if(snake[0].intersects(rewardNode))
    {
        count++;
        addNewReward();
    }
    // 检查是否与边界发生碰撞
    if (checkBoundaryCollision()||checkContact()) {
        gameStart = false;
        timer->stop();
        update(); // 请求重绘窗口以显示 GAME OVER
        return;
    }
    // 如果没有发生碰撞，继续游戏逻辑...
    while(count--)
    {
        switch(moveFlag)
        {
        case DIR_UP:
            addTop();//在顶部加一个方块
            break;
        case DIR_DOWN:
            addDown();
            break;
        case DIR_LEFT:
            addLeft();
            break;
        case DIR_RIGHT:
            addRight();
            break;
        default :
            break;
        }
    }

    deleteLast();
    update();
    }

void mywidget::addTop(){
    QPointF leftTop;
    QPointF rightBottom;

    if(snake[0].y()-nodeHeight<0)
    {
        leftTop=QPointF(snake[0].x(),this->height()- nodeHeight);
        rightBottom=QPointF(snake[0].x()+nodeWidth,this->height());
    }
    else{
        leftTop=QPointF(snake[0].x(),snake[0].y()-nodeHeight);
        rightBottom=snake[0].topRight();
    }

    leftTop=QPointF(snake[0].x(),snake[0].y()-nodeHeight);
    rightBottom =snake[0].topRight();

    snake.insert(0,QRectF(leftTop,rightBottom));
}

void mywidget::paintEvent(QPaintEvent *event){
    QPainter painter(this);
    QPen pen;
    QBrush brush;

    //背景图片
    QPixmap pix;
    pix.load(":/new/prefix1/image/labixixaoxin.jpg");
    painter.drawPixmap(0 ,0 ,1398 ,781,pix);
    if (pix.load(":/new/prefix1/image/labixixaoxin.jpg")) {
        // 获取窗口的大小
        int windowWidth = this->width();
        int windowHeight = this->height();

        // 缩放图片以适应窗口大小
        QPixmap scaledPixmap = pix.scaled(windowWidth, windowHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);

        // 绘制背景图片
        painter.drawPixmap(0, 0, scaledPixmap);
    } else {
        qDebug() << "Failed to load background image.";
    }

    //画蛇
    pen.setColor(Qt::yellow);
    brush.setColor(Qt::blue);
    brush.setStyle(Qt::SolidPattern);
    painter.setPen(pen);
    painter.setBrush(brush);

    for(int i=0;i<snake.length();i++){
    painter.drawRect(snake[i]); }

    QPixmap headPixmap, tailPixmap, bodyPixmap;

    // 加载蛇头图片
    headPixmap.load(":/new/prefix1/image/snake.head.jpg");
    // 加载蛇尾图片
    tailPixmap.load(":/new/prefix1/image/snake.tail.jpg");
    // 加载蛇身图片
    bodyPixmap.load(":/new/prefix1/image/snake.body.jpg");
    // 画蛇头
    if (!headPixmap.isNull()) {
        headPixmap = headPixmap.scaled(QSize(nodeWidth, nodeHeight), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        painter.drawPixmap(snake[0].topLeft(), headPixmap);
    }

    // 画蛇身中间部分
    if (!bodyPixmap.isNull()) {
        bodyPixmap = bodyPixmap.scaled(QSize(nodeWidth, nodeHeight), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        for (int i = 1; i < snake.length() - 1; ++i) {
            painter.drawPixmap(snake[i].topLeft(), bodyPixmap);
        }
    }

    // 画蛇尾
    if (!tailPixmap.isNull()) {
        tailPixmap = tailPixmap.scaled(QSize(nodeWidth, nodeHeight), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        painter.drawPixmap(snake.last().topLeft(), tailPixmap);
    }


    //画食物
    pen.setColor(Qt::red);
    brush.setColor(Qt::red);
    brush.setStyle(Qt::SolidPattern);
    painter.setPen(pen);
    painter.setBrush(brush);

    painter.drawEllipse(rewardNode);
    //food
    QPixmap rewardPixmap;
    rewardPixmap.load(":/new/prefix1/image/food.jpg");
    painter.drawPixmap(rewardNode.topLeft(),rewardPixmap);
    if (!rewardPixmap.isNull()) { // 确保图片已加载
        painter.drawPixmap(rewardNode.topLeft(), rewardPixmap);
    }
    if(!gameStart){
        QFont font("微软雅黑",30,QFont::ExtraLight,false);
        painter.setFont(font);
        painter.drawText((this->width()-300)/2,
                         (this->height()-30)/2,
                         QString("GAME OVER!"));
        //关闭定时器
        timer->stop();
    }

    QWidget::paintEvent(event);
}

void mywidget::deleteLast(){
    snake.removeLast();
}

void mywidget::addDown(){
    QPointF leftTop;
    QPointF rightBottom;
    if(snake[0].y()+nodeHeight*2>this->height())
    {
        leftTop=QPointF(snake[0].x(),0);
        rightBottom=QPointF(snake[0].x()+nodeWidth,nodeHeight);
    }
    else{
        leftTop=snake[0].bottomLeft();
        rightBottom=snake[0].bottomRight()+QPointF(0,nodeHeight);
    }


    snake.insert(0,QRectF(leftTop,rightBottom));
}

void mywidget::addLeft(){
    QPointF leftTop;
    QPointF rightBottom;
    if(snake[0].x()-nodeHeight<0)
    {
        leftTop=QPointF(this->width()-nodeWidth,snake[0].y());
    }
    else{
        leftTop=snake[0].topLeft()-QPointF(nodeWidth,0);
    }
    rightBottom=leftTop + QPointF(nodeWidth,nodeHeight);
    snake.insert(0,QRectF(leftTop,rightBottom));
}

void mywidget::addRight(){
    QPointF leftTop;
    QPointF rightBottom;
    if(snake[0].x()+nodeWidth*2>this->width())
    {
        leftTop=QPointF(0,snake[0].y());
    }
    else{
        leftTop=snake[0].topRight();

    }

    rightBottom=leftTop+QPointF(nodeWidth,nodeHeight);
    snake.insert(0,QRectF(leftTop,rightBottom));
}

//定义固定的食物尺寸
    const int fixedFoodWidth = 20;
    const int fixedFoodHeight = 20;

void mywidget::addNewReward(){
    int randomX = QRandomGenerator::global()->bounded((this->width()- fixedFoodWidth)  / 20) * 20;
    int randomY = QRandomGenerator::global()->bounded((this->height()- fixedFoodHeight)  / 20) * 20;

    QPixmap rewardPixmap;
    if (rewardPixmap.load(":/new/prefix1/image/food.jpg")) {
        // 调整图片尺寸以符合固定尺寸
        rewardPixmap = rewardPixmap.scaled(fixedFoodWidth, fixedFoodHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);

        // 更新食物的显示区域
        rewardNode = QRectF(randomX, randomY, fixedFoodWidth, fixedFoodHeight);
    } else {
        qDebug() << "Failed to load food image.";}
}

bool mywidget::checkBoundaryCollision() {
    QRectF head = snake[0];
    return head.right() > this->width() || // 蛇头超出右边界
           head.left() < 0 || // 蛇头超出左边界
           head.bottom() > this->height(); // 蛇头超出下边界
}
//游戏结束界面
bool mywidget::checkContact(){
    for(int i =1;i<snake.length();i++){
        for(int j =1+i;j<snake.length();j++){
            if(snake[i] == snake[j]){
                return true;
            }
        }
    return false;
}
}

